/**
 * Copyright © 2019, Wen Hao <wenhao@126.com>.
 * <p>
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * <p>
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * <p>
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.fourthdimension.jpa.specification;

import com.fourthdimension.jpa.common.JoinEntity;
import com.fourthdimension.jpa.common.JoinUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import java.io.Serializable;
import java.util.Set;


import javax.persistence.criteria.From;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;


abstract class AbstractSpecification<T> implements Specification<T>, Serializable {

    private JoinEntity joinEntity;

    protected AbstractSpecification getJoinEntity(String property) {
        this.joinEntity = JoinUtil.getJoinEntity(property);
        return this;
    }

    public String getProperty() {
        String[] properties = joinEntity.getProperties();
        if (StringUtils.isNotEmpty(properties[1])) {
            return properties[1];
        }
        return joinEntity.getProperty();
    }

    public From getRoot(Root<T> root) {

        // 获取连接查询的方式
        String[] properties = joinEntity.getProperties();
        JoinType joinType = joinEntity.getJoinType();

        if (joinType == null || StringUtils.isEmpty(properties[0])) {
            return root;
        }

        //防止多次join的情况
        Set<Join<T, ?>> joins = root.getJoins();
        for (Join<T, ?> join : joins) {
            if (join.getAttribute().getName().equals(properties[0])) {
                return join;
            }
        }
        switch (joinType) {
            case INNER:
                return root.join(properties[0], JoinType.INNER);
            case LEFT:
                return root.join(properties[0], JoinType.LEFT);
            default:
                return root;
        }
    }

}



